import axios from 'axios'
axios.interceptors.request.use(success => {
  var arr = []
  document.cookie.split(';').map(res => {
    arr = arr.concat(res.split('='))
  })
  success.headers['token'] = arr[arr.length - 1]
  return success
}, err => {
  // console.log(err)
  return err
})
axios.interceptors.response.use(success => {
  // console.log('header',success.headers)
  document.cookie = `token=${success.headers['setcookie']}`
  return success
}, err => {
  console.log(err)
  return err
})
let cancelToken = axios.CancelToken
class Http {
  cancelToken = false // false不取消发送 true 取消发送
  self = this
  header = {
    timeout: 3000,
    url: '',
    baseURL: '',
    method: '',
    params: '',
    data: '',
    responseType: 'json',
    cancelToken: '',
    headers: {
      name: 1
    },
    withCredentials: false,
    onUploadProgress: progressEvent => {
      let complete = (progressEvent.loaded / progressEvent.total * 100 | 0) + '%'
      console.log('123',complete)
    }
  }
  constructor() {
    this.get = this.getInfo
    this.post = this.postInfo
    this.fileupload = this.fileuploadInfo
    this.fileUploadProgress = this.fileProgress
  }
  cancal() {
    this.header.cancelToken = new cancelToken(function (res) {
      res('取消发送')
    })
  }
  fileProgress(url, data, header,cancal = false) {
    if (cancal) {
      this.cancal()
    }
    return axios.post(url, data, Object.assign(this.header, {
      ...header,
      "content-type": "multipart/form-data"
    }))
  }
  getInfo(url, data, cancal = false) {
    if (cancal) {
      this.cancal()
    }
    this.header.url = url
    this.header.params = data
    this.header.method = 'get'
    return axios({
      ...this.header
    })
  }
  postInfo(url, data, cancal = false) {
    if (cancal) {
      this.cancal()
    }
    this.header.url = url
    this.header.data = data
    this.header.method = 'post'
    return axios({
      ...this.header
    })
  }
  fileuploadInfo(url, form, cancal = false) {
    if (cancal) {
      this.cancal()
    }
    this.header.url = url
    this.header.data = form
    this.header.method = 'post'
    this.header.responseType = 'json'
    return axios({
      ...this.header
    })
  }
}
const api = new Http()
export default api